<template>
    <app-container>
        <app-block>
            <el-tabs v-model="tabType" class="wp100 vm" @tab-click="tabTypeChange">
                <el-tab-pane :label="item.label" :name="item.value" v-for="(item, index) in CUSTOMER_SET_TAB" :key="index" />
            </el-tabs>
            <div v-if="tabType === '9'">
                <el-card :body-style="{ padding: '0px', margin: '0 10px 0 12px' }">
                    <div class="pd15 lh30 fs16">
                        <div class="mb10">客户限时回流公海：</div>
                        <div>
                            超过系统设置的x天无订单，无跟进记录，则客户会自动回到公海中
                        </div>
                        <div>系统会在客户即将流入公海的前3天内提醒所属业务员</div>
                        <div>
                            客户回到公海后，前所属业务员不可立即领取，需满足设置的x天后才可领取
                        </div>
                    </div>
                </el-card>
                <zm-table :data="tableData" :show-header="false" :border="false">
                    <zm-table-column align="left">
                        <template slot-scope="scope">
                            <el-card :body-style="{ padding: '0px' }">
                                <div style="padding: 14px;">
                                    <zm-switch :value="scope.row.status" active-value="1" inactive-value="0" @change="onSwitch(scope.row)" />
                                    <span class="text-primary fs16 ml10">{{ scope.row.switchName }}</span>
                                    <span class="fr" style="color:#409eff;font-size:16px;cursor:pointer" v-if="scope.row.status === '1'" @click="myEdit(scope.row)">编辑回流规则</span>
                                </div>
                                <div class="pd15">
                                    <div v-for="(item, index) in scope.row.publicDaySet" :key="index" class="mb10">
                                        <!-- 天数类型  1 产生过销售单   2 未产生过销售单 -->
                                        <span v-if="scope.row.switchName === '客户限时回流公海'">
                                            <span v-if="item.customerType === '1'">
                                                企业客户:
                                                <span v-if="item.daysType === '1'">
                                                    <span>产生过销售单客户，超过{{ item.days }}天
                                                        未有新销售单产生会被系统移入公海 &nbsp;</span>
                                                </span>
                                                <span v-if="item.daysType === '2'">
                                                    <span>未产生过销售单客户，超过</span>
                                                </span>
                                            </span>
                                            <span v-if="item.customerType === '2'">
                                                个人客户:
                                                <span v-if="item.daysType === '1'">
                                                    <span>产生过销售单客户，超过{{ item.days }}天
                                                        未有新销售单产生会被系统移入公海 &nbsp;</span>
                                                </span>
                                                <span v-if="item.daysType === '2'">
                                                    <span>未产生过销售单客户，超过</span>
                                                </span>
                                            </span>

                                            <span v-if="item.customerType === '3'">
                                                地产客户:
                                                <span v-if="item.daysType === '1'">
                                                    <span>产生过销售单客户，超过{{ item.days }}天
                                                        未有新销售单产生会被系统移入公海 &nbsp;</span>
                                                </span>
                                                <span v-if="item.daysType === '2'">
                                                    <span>未产生过销售单客户，超过</span>
                                                </span>
                                            </span>

                                            <span v-if="item.customerType === '0'">
                                                在公海池内的所有客户:
                                                <span v-if="item.daysType === '1'">
                                                    <span>产生过销售单客户，超过{{ item.days }}天
                                                        未有新销售单产生会被系统移入公海 &nbsp;</span>
                                                </span>
                                                <span v-if="item.daysType === '2'">
                                                    <span>未产生过销售单客户，超过</span>
                                                </span>
                                            </span>
                                        </span>
                                        <!-- 天数类型为  3 客户跟踪   4 业务员领取客户 -->
                                        <span v-if="item.daysType === '3' || item.daysType === '4'">{{
                      item.customerType === '1'
                        ? '企业客户超过'
                        : item.customerType === '2'
                        ? '个人客户超过'
                        : item.customerType === '0'
                        ? '在公海池内的所有客户超过'
                        : '地产客户超过'
                    }}</span>
                                        <span v-if="item.daysType !== '1'">{{ item.days }}天</span>
                                        <span v-if="item.daysType === '2' || scope.row.switchName !== '客户限时回流公海'">
                                            {{
                        scope.row.id === '1'
                          ? '未有销售单产生的客户会被系统放回公海'
                          : scope.row.id === '2'
                          ? '未产生跟进记录的客户会被系统放回公海'
                          : '内原所属业务员不可领取'
                      }}
                                        </span>
                                    </div>
                                </div>
                            </el-card>
                        </template>
                    </zm-table-column>
                </zm-table>
            </div>
            <div v-else-if="!loading">
                <zm-form :model="form" ref="searchForm" inline v-if="tabType === '6'">
                    <el-form-item label="客户名称" prop="customerName">
                        <zm-input v-model.trim="form.customerName" placeholder="请输入客户名称" class="w300" />
                    </el-form-item>
                    <el-form-item label="所属行业" prop="tradeType">
                        <zm-data-select v-model="form.tradeType" k1="tradeType" placeholder="请选择所属行业" multiple str class="w300"></zm-data-select>
                    </el-form-item>
                    <zm-form-item>
                        <zm-button @click="onSearch" t="search"></zm-button>
                        <zm-button @click="onReset" t="reset"></zm-button>
                        <zm-button @click="onNew" t="add" />
                        <zm-button type="warning" @click="onExport">
                            导出
                        </zm-button>
                        <zm-export ref="export" :api="exportApi()" type="warning" :params="exportForm" v-show="false"></zm-export>
                    </zm-form-item>
                </zm-form>
                <zm-button @click="onNew" t="add" class="mb10" v-else />
                <zm-table-data ref="multipleTable" :data="tableParams.data" :columns="columns" :fetch="loadList" :table-params="tableParams" @selection-change="saveIds" :mutilple="tabType === '6'">
                </zm-table-data>
            </div>
        </app-block>
        <new-panel v-if="newParams.visible" v-model="newParams.visible" :set-type="tabType" :obj="newParams.obj" @after="loadList"></new-panel>

        <switch-dialog v-if="isVisibleDialog" v-model="isVisibleDialog" :obj="currentObj" @mySubmit="getPublic"></switch-dialog>
    </app-container>
</template>

<script>
import tableMixin from '@/mixins/zmTableMixin'
import newPanel from './components/New'
import { customerSourceColumns } from './const'
import SwitchDialog from './SwitchDialog.vue'
import customerSet, {
  getPublicSet,
  updatePublicSwitch,
  updatePublicDay,
  getTypePageList,
  checkType,
  deleteType
} from '@/api/src/customerSet'

export default {
  name: 'CustomerSet',
  components: { SwitchDialog, newPanel },
  mixins: [tableMixin],
  data () {
    return {
      tabType: '9',
      CUSTOMER_SET_TAB: [
        { label: '公海设置', value: '9', spec: '1' },
        { label: '客户来源', value: '1' },
        { label: '所属行业', value: '2' },
        { label: '客户类型', value: '3' },
        { label: '业务场景', value: '5' },
        { label: '客户管理', value: '6' }
      ],
      tableData: [{}],
      newParams: {
        visible: false,
        setType: '',
        obj: {}
      },
      loading: false,
      isVisibleDialog: false,
      currentObj: {},
      form: {
        customerName: '',
        tradeType: ''
      },
      exportForm: {}
    }
  },
  computed: {
    columns () {
      return customerSourceColumns(this)
    }
  },
  watch: {},
  created () {
    this.getPublic()
  },
  methods: {
    async getPublic () {
      const tableData = await getPublicSet()
      this.tableData = [tableData[2]]
    },
    exportApi () {
      return customerSet.export
    },
    async onExport () {
      const form = this.tabType === '6' ? this.form : {}
      this.exportForm = { ...{ tabType: this.tabType, ids: this.ids }, ...form }
      this.$refs.export.onExport()
    },
    saveIds (selection, row) {
      // 保存已选
      this.ids = selection.map((item) => item.id).join(',')
    },
    tabTypeChange () {
      this.tableParams.page = 1
      this.loading = true
      this.$nextTick(() => {
        this.loading = false
      })
      if (this.tabType === '9') {
        return
      }
      this.tableParams.page = 1
      // this.onSearch() // 防止切换page没还原为1
    },
    async onSwitch (row) {
      let status = row.status === '0' ? '1' : '0'
      if (status === '1') {
        this.currentObj = JSON.parse(JSON.stringify(row))
        this.isVisibleDialog = true
        return
      }
      // let text = row.status === '1' ? '关闭' : '开启'
      // this.$confirm(`是否确认将【${row.switchName}】` + text + '？', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(async () => {
      // 开关状态，0关闭，1开启
      await updatePublicSwitch({
        id: row.id,
        status: status
      })
      this.getPublic()
      // })
    },
    async changeInputData (id, days, daysType) {
      const reg = /^[1-9]\d*$/
      if (!reg.test(days)) {
        this.getPublic()
        this.$message.error('天数应为正整数,请重新填写')
        return
      }
      await updatePublicDay({ customerPublicData: [{ id: id, days: days, daysType: daysType }] })
    },
    async loadList () {
      const form = this.tabType === '6' ? this.form : {}
      const res = await getTypePageList(this.assignQuery({ ...{ tabType: this.tabType }, ...form }))
      this.initialTableData(res.list, res.count)
    },
    onNew () {
      this.newParams = {
        visible: true,
        setType: this.tabType,
        obj: {}
      }
    },
    onEdit (row) {
      this.newParams = {
        visible: true,
        setType: this.tabType,
        obj: row
      }
    },
    onConfirmDele (tabTypeName, id) {
      this.$confirm(`是否确认删除该${tabTypeName}？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await deleteType({ id, type: this.tabType })
        await this.$store.dispatch('setTypeList', 'forceFresh')
        this.loadList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    },
    onDelete (row) {
      let tabTypeName
      switch (this.tabType) {
        case '1':
          tabTypeName = '客户来源'
          break
        case '2':
          tabTypeName = '客户行业'
          break
        case '3':
          tabTypeName = '客户类型'
          break
        case '5':
          tabTypeName = '业务场景'
          break
        case '6':
          tabTypeName = '客户信息'
          break
        default:
          tabTypeName = ''
          break
      }
      if (this.tabType !== '6') {
        checkType({ id: row.id, type: this.tabType })
          .then((res) => {
            if (!res.isCan) {
              this.$message.error(res.tipMessage)
              return
            } else {
              this.onConfirmDele(tabTypeName, row.id)
            }
          })
          .catch((e) => {
            return
          })
      } else {
        this.onConfirmDele(tabTypeName, row.id)
      }
    },
    handleClose (done) {
      done()
    },
    myEdit (row) {
      this.isVisibleDialog = true
      this.currentObj = JSON.parse(JSON.stringify(row))
    }
  }
}
</script>
